package com.bawei.caohao20240805.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

/**
 * 作者: 曹浩
 * 时间: 2024/8/5
 * 功能描述:
 */
abstract class BaseFragment<V:ViewModel,D:ViewDataBinding>(private var layout:Int) :Fragment(){
    lateinit var mViewModel:V
    lateinit var mDing:D
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mDing=DataBindingUtil.inflate(inflater,layout,container,false)
        mDing.lifecycleOwner=this
        return mDing.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        var type = javaClass.genericSuperclass as ParameterizedType
        var vClass = type.actualTypeArguments[0] as Class<V>
        mViewModel=ViewModelProvider(this)[vClass]
        initView()
        dataObSer()
    }

    abstract fun dataObSer()

    abstract fun initView()

    override fun onDestroy() {
//        18．避免内存泄漏
        super.onDestroy()
        if(mDing!=null){
            mDing.unbind()
        }
    }

}